﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.IO;

public class TObjectManager : MonoBehaviour {

	static int maxCount = 50;											//同时下载最大线程数
	static List<WWWObject> ResQueue = new List<WWWObject>();			//等待下载的队列信息
	
	static List<WWWObject> downLoadingList = new List<WWWObject>();		//正在下载的队列信息
	
	static List<WWW> DownLoaddingList = new List<WWW>();				//正在下载的实际对象
	
	static List<TMyFile> CreattingList = new List<TMyFile>();			//正在创建的实际对象

	static TObjectManager instance;
	
	public static TObjectManager GetInstances()
	{
		return instance;
	}
	
	void Awake()
	{
		instance = this;
	}
	
	/// <summary>
	/// 检测待创建的资源是否正在创建列表中
	/// url 资源路径
	/// </param>
	static TMyFile GetCreating(string url)
	{
		foreach(TMyFile www in CreattingList)
		{
			if(www.url == url)
				return www;
		}
		
		return null;
	}
	
	static WWW GetWWW(string url)
	{
		foreach(WWW www in DownLoaddingList)
		{
			if(www.url == url)
				return www;
		}
		return null;
	}
	
	/// <summary>
	/// 添加一个待下载资源
	/// parameter 自定义参数
	/// url 资源路径
	/// method 资源下载完成后的代理
	/// </param>
	public void Load(object parameter, string url, WWWObject.OnLoadOver method)
	{
//		string lstr = "load " + url;
		ResQueue.Add(new WWWObject(parameter, url, method));
	}
	
	public static void ReleaseAll()
	{
		foreach(TMyFile mf in CreattingList)
		{
			if(mf.ac != null && mf.ac.assetBundle != null)
				mf.ac.assetBundle.Unload(true);
		}
		CreattingList.Clear();
	}
	
	IEnumerator LoadFromDisk(TMyFile myf)
	{
		WWW pf = new WWW(myf.url);
		yield return pf;
		
		if(pf.isDone)
		{
			if(pf.error != null)
			{
				string msg = pf.url + " 加载错误！ ";
				Debug.LogError(msg);
			}
			else
			{
				byte[] jiemi = tcom.tools.TEncodeFile.DecryptDES(pf.bytes);
				myf.ac = AssetBundle.CreateFromMemory(jiemi);
			}
		}
		else
		{
			Debug.LogError(pf.error);
		}
	}
	
	TMyFile AddWWWLoad(string url)
	{
		TMyFile pf = GetCreating(url);
		if(pf == null)
		{
			//如果没有，那么创建一个
			pf = new TMyFile();
			pf.url = url;
			CreattingList.Add(pf);
			
			StartCoroutine(LoadFromDisk(pf));
		}
		return pf;
	}
	
	bool CheckCreatingNum()
	{
		int unum = 0;
		for(int i = 0; i < CreattingList.Count; i++)
		{
			if(CreattingList[i].ac == null || !CreattingList[i].ac.isDone)
			{
				unum++;
				if(unum > maxCount)
				{
					return false;
				}
			}
		}
		return true;
	}
	
	/// <summary>
	/// 更新队列信息
	/// </summary>
	void UpdateQueue()
	{
		//如果下载队列空闲， 则检测是否还有待下载资源
		if(CheckCreatingNum())
		{
			if(ResQueue.Count > 0)
			{
				//检测本地是否有该文件, 如果有, 那么开始下载
				
				int procnum = 0;
				while(procnum < 1 && ResQueue.Count > 0)
				{
					WWWObject w3Obj = ResQueue[0];
					w3Obj.resource = AddWWWLoad(w3Obj.url);
					downLoadingList.Add(w3Obj);
					
					//从下载列表中删除该项
					ResQueue.RemoveAt(0);
					procnum++;
				}
			}
		}
	}
	
	public bool bShowDownLoadingList = false;
	void OnGUI()
	{
		if(bShowDownLoadingList)
		{
			int i = 1;
			foreach (WWWObject dl in downLoadingList)
			{
				if(dl.resource.ac != null)
				{
					GUI.Label(new Rect(10, i * 25, 10000, 20), dl.url + "%" + dl.resource.ac.progress * 100);
				}
				else
				{
					GUI.Label(new Rect(10, i * 25, 10000, 20), dl.url + " error ");
				}
				i++;
			}
		}
	}
	
	void Update()
	{
		UpdateQueue();
		int procnum = 0;
		int i = 0;
		
		while(procnum < 1 && i < downLoadingList.Count)
		{
			WWWObject dl = downLoadingList[i];
			if(dl.resource.ac != null && dl.resource.ac.isDone)
			{
//				string pff = dl.url + " createdown";
				if(dl.onLoadOver != null)
				{
					dl.onLoadOver(dl.parameter, dl.resource);
				}
				
				downLoadingList.RemoveAt(i);
				procnum++;
			}
		}
	}
}
